package org.tlang.ast.list.statement;

import org.tlang.ast.AST;
import org.tlang.ast.ASTList;
import org.tlang.context.TypeTable;
import org.tlang.context.ValueTable;
import org.tlang.exception.TypeException;
import org.tlang.metaclass.TReturn;
import org.tlang.type.ReturnType;
import org.tlang.type.Type;
import org.tlang.type.VoidType;

import java.util.List;

public class BlockStatement extends ASTList {
    public BlockStatement(List<AST> children) {
        super(children);
    }

    @Override
    public Object eval(ValueTable valueTable) {
        Object result;
        for (AST ast : children()) {
            result = ast.eval(valueTable);
            if (result instanceof TReturn) { // return 结果阻断后续语句执行
                return result;
            }
        }
        return TReturn.VOID;
    }

    @Override
    public Type typeCheck(TypeTable typeTable) throws TypeException {
        ReturnType result = null;
        for (AST ast : children()) {
            Type type = ast.typeCheck(typeTable);
            if (type instanceof ReturnType) {
                if (result != null) {
                    result.assertTypeOf(type, ast);
                }
                result = (ReturnType) type;
            }
        }
        return result == null ? VoidType.VOID_TYPE : result;
    }
}
